<template>
  <el-dialog
    width="800"
    :title="'实物券' + dialogTitle"
    v-model="visible"
    draggable
    @close="closeDialog"
  >
    <div class="title">基本设置</div>
    <el-form
      :disabled="dialogTitle.includes('详情')"
      :model="formParams"
      ref="formRef"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input
          v-model.trim="formParams.couponName"
          placeholder="请输入优惠券名称，最多16字"
          maxlength="16"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="名称备注" prop="remark">
        <el-input
          v-model.trim="formParams.remark"
          placeholder="仅内部可见，最多30字"
          maxlength="30"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="发放总量" prop="count">
        <el-input-number
          @mousewheel.native.prevent
          :controls="false"
          style="width: 240px"
          v-model="formParams.count"
          :max="100000"
          :min="1"
          :precision="0"
          controls-position="right"
          placeholder="最多100000"
        />&nbsp;张
      </el-form-item>
      <el-form-item label="用券时间" prop="activityTime">
        <div>
          <el-date-picker
            v-model="formParams.activityTime"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            date-format="YYYY-MM-DD"
            time-format="HH:mm"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </div>
      </el-form-item>
      <el-form-item label="每人限领次数" prop="receiveCount">
        <el-input-number
          @mousewheel.native.prevent
          :controls="false"
          style="width: 240px"
          v-model="formParams.receiveCount"
          :max="200"
          :min="1"
          :precision="0"
          controls-position="right"
          placeholder="请输入整数"
        />&nbsp;次
        <div style="width: 100%; color: red">最大设置200次</div>
      </el-form-item>
      <el-form-item label="使用规则" prop="rule">
        <div style="width: 100%">
          <el-input
            v-model="formParams.rule"
            style="width: 300px"
            :autosize="{ minRows: 3, maxRows: 8 }"
            type="textarea"
            maxlength="1000"
            placeholder="请输入内容"
            show-word-limit
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer v-if="!dialogTitle.includes('详情')">
      <el-button type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  addActivityApi,
  checkPopupApi,
  getComboListApi,
  getCouponDetailApi,
  getPositionListApi
} from '@/api/marketing/activity'
import { formatTexarea } from '@/utils/tools'

const visible = ref(false)
const dialogTitle = ref('详情')
const formParams = ref({
  couponName: null,
  remark: null,
  count: null,
  activityTime: null,
  receiveCount: null,
  rule: null,
  cityName: inject('cityName')
})
const formRef = ref()

const rules = {
  couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  count: [{ required: true, message: '请输入发放总量', trigger: ['blur', 'change'] }],
  activityTime: [{ required: true, message: '请选择用券时间', trigger: 'change' }],
  receiveCount: [{ required: true, message: '请输入每人限领次数', trigger: 'blur' }],
  rule: [{ required: true, message: '请输入使用规则', trigger: 'blur' }]
}
function init(row, title) {
  if (title === 'edit') {
    dialogTitle.value = '编辑'
  } else if (title === 'add') {
    dialogTitle.value = '新增'
  } else {
    dialogTitle.value = '详情'
    console.log({ row })
    getCouponDetailApi({ couponId: row.id }).then((res) => {
      console.log(res)
      const params = { ...formParams.value }
      delete params.cityName
      Object.keys(params).find((i) => {
        formParams.value[i] = res.data[i]
      })
      formParams.value.activityTime = [res?.data?.validStartTime, res?.data?.validEndTime]
      formParams.value.rule = formatTexarea(res?.data?.rule, 1)
      visible.value = true
    })
  }
  visible.value = true
}
function handleAction(confirm) {
  // console.log(formParams.value.cityName)
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid) {
        const params = {
          ...formParams.value,
          type: 6,
          rule: formatTexarea(formParams.value.rule),
          validStartTime: new Date(formParams.value.activityTime[0] + ':00').getTime(),
          validEndTime: new Date(formParams.value.activityTime[1] + ':59').getTime(),
          comboIdList: [],
          positionIdList: [],
          popup: 0
        }
        delete params.activityTime
        addActivityApi(params)
          .then(() => {
            ElMessage({
              message: '活动新建成功',
              type: 'success'
            })
            emit('refresh')
            closeDialog()
          })
          .catch(() => {})
      }
    })
  } else {
    closeDialog()
  }
}
const emit = defineEmits(['refresh'])
function closeDialog() {
  formRef.value.resetFields()
  visible.value = false
}
defineExpose({
  init
})
</script>
<style lang="scss" scoped>
.title {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
}
</style>
